package cn.itcast.core.service.staticpage;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.ServletContext;
import java.io.*;
import java.util.Map;


// 不用注解，用配置xml的方式注入
public class StaticPageServiceImpl implements ServletContextAware{

	Configuration configuration;

	// 由配置中注入 FreeMarkerConfigurer属性来调用。
	public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer){
		this.configuration =  freeMarkerConfigurer.getConfiguration();
	}

	public String pageIndex(Map<String,Object> root,Integer id){
		// 设置模板目录,在 freemarker.xml里配置:<property name="templateLoaderPath" value="/WEB-INF/ftl"/>
		// configuration.setDirectoryForTemplateLoading(new File('dir'));
		//设置默认字符 ，freemarker.xml里配置
		// configuration.setDefaultEncoding("UTF-8");
		// 输入流
		Writer out= null;
		try {
			Template template = configuration.getTemplate("productDetail.html");
			//获取Html的路径
			String path = getPath("/html/product/" + id +  ".html");//278.html

			File f = new File(path);
			File parentFile = f.getParentFile();
			if(!parentFile.exists()){
				parentFile.mkdirs();
			}
			// 获取或创建一个模版。

			//用utf-8编码 写出去
			out = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
			template.process(root, out);
		} catch (IOException e) {
			//e.printStackTrace();
		} catch (TemplateException e) {
			//e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "/html/product/" + id +  ".html";

	}

	//获取路径
	public String getPath(String name){
		return servletContext.getRealPath(name);
	}
	// 注入上下文
	ServletContext servletContext;
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

}
